package com.example.AIstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.AIstudy.dao.UserDao;
import com.example.AIstudy.domain.User;
import com.example.AIstudy.exception.AIstudyException;
import com.example.AIstudy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {
    @Autowired
    UserDao userDao;
//    @Autowired
//    PasswordEncoder passwordEncoder;

    //根据用户名获取用户信息
    @Cacheable(cacheNames = "userbyName",key = "#name",condition = "#name!=null")
    @Override
    public User getUserByUserName(String name){
        //获取到user对象
        User user=userDao.getUserByUserName(name);
        return user;
    }

    //根据用户id获取用户信息
    @Override
    @Cacheable(cacheNames = "userbyID",key = "#id",condition = "#id!=null")
    public User getUserByUserID(Integer id){
        return userDao.selectById(id);
    }

    //增加一条用户记录
    @Override
    public User insertUser(User user) throws AIstudyException{
        try{
            userDao.insertUser(user);
            return user;
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.INSERT_ERROR,"添加用户信息失败");
        }
    }

    //修改一条用户信息
    @Transactional(rollbackFor = AIstudyException.class)
    @Override
    @CacheEvict(cacheNames = "userbyID",key = "#user.id")
    public void updateUserByID(User user) throws AIstudyException{
        try{
            //修改信息
            userDao.updateById(user);
        }catch (Exception e){
            throw new AIstudyException(AIstudyException.ErrorType.UPDATE_ERROR,"修改用户信息失败");
        }
    }

    //分页获取用户信息
    @Override
    public IPage<User> findUsers(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        IPage page = new Page(pageNum, pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.like(condition.containsKey("username"), "nickname", condition.get("name"));
        return userDao.findUsers(page, qw);
    }

    public User getUserByOpenID(String openID){
        return userDao.getUserByOpenID(openID);
    }

    public List<Integer> getAllUserID(){
        return userDao.getAllUserID();
    }
}

